﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace ThienLoc.Admin
{
    public partial class QuanTriMenu : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FormThaoTac.Visible = false;
            if (!IsPostBack)
            {
                LoadMenuData();
            }
        }

        private void LoadMenuData()
        {
            string sql = "SELECT * FROM dbo.tblTLMenu";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            foreach (DataRow item in dt.Rows)
            {
                TreeView1.Nodes.Add(new TreeNode(item["Ten"].ToString(), item["ID"].ToString()));
            }
        }

        private void LoadDataToControls(int mID)
        {
            string sql = "SELECT * FROM dbo.tblTLMenu WHERE ID = " + mID;
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            txtTen.Text = dt.Rows[0]["Ten"].ToString();
            imgMenu.ImageUrl = "../" + dt.Rows[0]["Image"].ToString();
        }

        protected void btnCapNhat_Click(object sender, EventArgs e)
        {
            if (btnCapNhat.CommandName == MyConst.Action.Addnew)
            {
                ThemMoiMenu();
            }
            else
            {
                CapNhatMenu();
            }
            TreeView1.ExpandAll();
        }

        private void ThemMoiMenu()
        {
            string sql = "INSERT INTO dbo.tblTLMenu(Ten,ParentID,IsShowUp,CreateDate,UpdateDate)" +
                        "VALUES(@Ten,NULL,@IsShowUp,GETDATE(),GETDATE())";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@Ten", SqlDbType.NVarChar, ParameterDirection.Input, txtTen.Text));
            int HienThi = 0;
            arrParams.Add(SqlHelper.CreateParameterObject("@IsShowUp", SqlDbType.Int, ParameterDirection.Input, HienThi));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
            TreeView1.Nodes.Clear();
            LoadMenuData();
        }

        protected void btnXoa_Click(object sender, EventArgs e)
        {
            string sql = "SELECT * FROM dbo.tblTLMenu WHERE ID = " + MenuID.Value;
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            if (dt.Rows[0]["ParentID"] != null)
            {
                XoaMenu();
            }
        }

        protected void XoaMenu()
        {
            string sql = "DELETE FROM dbo.tblTLMenu WHERE ID = @ID";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, MenuID.Value));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
            TreeView1.Nodes.Clear();
            LoadMenuData();
        }

        protected void CapNhatMenu()
        {
            string updatefile = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            if (imgMenuUploadFile.HasFile)
            {
                updatefile = "Image = @Image";
                arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile()));
            }
            string sql = "UPDATE dbo.tblTLMenu SET Ten = @Ten," + updatefile + " WHERE ID = @ID";
            arrParams.Add(SqlHelper.CreateParameterObject("@Ten", SqlDbType.NVarChar, ParameterDirection.Input, txtTen.Text));
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, MenuID.Value));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
            TreeView1.Nodes.Clear();
            LoadMenuData();
        }

        protected void btnThem_Click(object sender, EventArgs e)
        {
            ResetField();
            btnCapNhat.CommandName = MyConst.Action.Addnew;
            btnCapNhat.Text = "Lưu lại";
            btnXoa.Visible = false;
            btnCapNhat.Visible = true;
            FormThaoTac.Visible = true;
        }

        protected void ResetField()
        {
            txtTen.Text = "";
            imgMenu.ImageUrl = "";
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            FormThaoTac.Visible = false;
            ResetField();
        }

        protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
        {
            LoadDataToControls(Convert.ToInt32(TreeView1.SelectedValue));
            FormThaoTac.Visible = true;
            btnCapNhat.Visible = true;
            btnXoa.Visible = true;
            btnCapNhat.Text = "Cập nhật";
            btnCapNhat.CommandName = MyConst.Action.Update;
            MenuID.Value = TreeView1.SelectedValue;
        }

        private string UploadFile()
        {
            try
            {
                if (imgMenuUploadFile.HasFile)
                {
                    string sFolderPath = Server.MapPath(@"../uploads/imgmenu");
                    HttpPostedFile myFile = imgMenuUploadFile.PostedFile;
                    string sFileName = myFile.FileName;
                    string[] arrFileName = sFileName.Split('.');
                    arrFileName[0] = arrFileName[0].Replace(' ', '_') + "_" + DateTime.Now.ToString("ddMMyyhhssmm");
                    sFileName = arrFileName[0] + "." + arrFileName[1];

                    // Create a bitmap of the content of the fileUpload control in memory
                    Bitmap originalBMP = new Bitmap(imgMenuUploadFile.FileContent);

                    // Calculate the new image dimensions
                    float origWidth = originalBMP.Width;
                    float origHeight = originalBMP.Height;
                    float sngRatio;
                    int newWidth = 210;
                    int newHeight;
                    if (origHeight > origWidth)
                    {
                        sngRatio = origHeight / origWidth;
                        newHeight = Convert.ToInt32(newWidth * sngRatio);
                    }
                    else
                    {
                        sngRatio = origWidth / origHeight;
                        newHeight = Convert.ToInt32(newWidth / sngRatio);
                    }
                    // Create a new bitmap which will hold the previous resized bitmap
                    Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

                    // Create a graphic based on the new bitmap
                    Graphics oGraphics = Graphics.FromImage(newBMP);
                    // Set the properties for the new graphic file
                    oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    // Draw the new graphic based on the resized bitmap
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                    // Save the new graphic file to the server
                    newBMP.Save(string.Format(@"{0}\{1}", sFolderPath, sFileName));

                    // Once finished with the bitmap objects, we deallocate them.
                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    //myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                    return "uploads/imgmenu/" + sFileName;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
